package com.project.xsf.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.JunM.entity.SGather;
import com.project.JunM.entity.SGatherDetails;
import com.project.JunM.entity.SPay;
import com.project.JunM.entity.SPayDetails;
import com.project.JunM.service.SGatherDetailsService;
import com.project.JunM.service.SGatherService;
import com.project.JunM.service.SPayDetailsService;
import com.project.JunM.service.SPayService;
import com.project.common.entity.PageVo;
import com.project.common.entity.SysUsers;
import com.project.common.utils.Serial;
import com.project.xsf.entity.*;
import com.project.xsf.service.*;
import com.project.xy.entity.DFile;
import com.project.xy.service.DFileService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mManufacture")
public class MManufactureController {
    @Autowired
    private MManufactureService mManufactureService;
    @Autowired
    private MApplyService mApplyService;
    @Autowired
    private SPayService sPayService;
    @Autowired
    private MProcedureService mProcedureService;
    @Autowired
    private MProcedureModuleService mProcedureModuleService;
    @Autowired
    private MDesignProcedureModuleService mDesignProcedureModuleService;
     @Autowired
        private DFileService dFileService;
     @Autowired
        private SPayDetailsService sPayDetailsService;
 @Autowired
        private SGatherService sGatherService;
     @Autowired
        private SGatherDetailsService sGatherDetailsService;

    @ResponseBody
    @PostMapping("/addMManufacture.action")
    public  void addMManufacture(String mApplyIdsStr,String mManufactureStr,String mProcedureArrs) throws IOException {
        Integer[] mApplyIds = JSONObject.parseObject(mApplyIdsStr, Integer[].class);
        MManufacture mManufacture = JSONObject.parseObject(mManufactureStr, MManufacture.class);
        MProcedure[] mProcedures = JSONObject.parseObject(mProcedureArrs, MProcedure[].class);

        String applyIdGroup="";
        for(int i=0;i<mApplyIds.length;i++){
            MApply mApply = mApplyService.selectByPrimaryKey(mApplyIds[i]);
            mApply.setManufactureTag("P001-1");
            mApplyService.updateByPrimaryKeySelective(mApply);
//                    System.out.println(mApply);
            applyIdGroup+=mApply.getId();
            if(i<mApplyIds.length-1){
                applyIdGroup+="|";
            }
        }
        mManufacture.setApplyIdGroup(applyIdGroup);
        mManufacture.setRealLabourCostPriceSum(0.0);
        mManufacture.setRealModuleCostPriceSum(0.0);

        mManufactureService.insertSelective(mManufacture);
//        System.out.println(mManufacture);

        for(int i=0;i<mProcedures.length;i++){
            MProcedure mProcedure = mProcedures[i];
            mProcedure.setParentId(mManufacture.getId());
            //获取MDesignProcedureDetailsId
            Integer MDesignProcedureDetailsId = mProcedure.getId();
            mProcedure.setId(null);
            mProcedure.setDemandAmount(Double.parseDouble(mManufacture.getAmount()+""));
            mProcedure.setRealLabourHourAmount(0.0);
            mProcedure.setRealModuleSubtotal(0.0);
            mProcedure.setRealSubtotal(0.0);
            mProcedureService.insertSelective(mProcedure);
            List<MDesignProcedureModule> mDesignProcedureModules = mDesignProcedureModuleService.queryMDesignProcedureModuleByPId(MDesignProcedureDetailsId);
            for(int j=0;j<mDesignProcedureModules.size();j++){
                MDesignProcedureModule mDesignProcedureModule = mDesignProcedureModules.get(j);
                MProcedureModule mProcedureModule = new MProcedureModule();
                mProcedureModule.setParentId(mProcedure.getId());
                mProcedureModule.setDetailsNumber(j+1);
                mProcedureModule.setCostPrice(mDesignProcedureModule.getCostPrice());
                mProcedureModule.setProductId(mDesignProcedureModule.getProductId());
                mProcedureModule.setProductName(mDesignProcedureModule.getProductName());
                mProcedureModule.setAmount(mDesignProcedureModule.getAmount()*mManufacture.getAmount());
                mProcedureModule.setSubtotal(mDesignProcedureModule.getSubtotal()*mManufacture.getAmount());
//                System.out.println(mProcedureModule);
                mProcedureModule.setRealAmount(0);
                mProcedureModule.setRenewAmount(0);
                mProcedureModule.setRealSubtotal(0.0);
                mProcedureModuleService.insertSelective(mProcedureModule);
            }

//            System.out.println(mProcedure.toString());
        }
    }
    @ResponseBody
    @PostMapping("/queryMManufactureNoCheck.action")
    public PageVo<MManufacture> queryMManufactureNoCheck(@RequestBody Map<String,String> map){
        PageVo<MManufacture> mManufacturePageVo = mManufactureService.queryMManufactureNoCheck(map);
        return mManufacturePageVo;
    }
    @ResponseBody
    @PostMapping("/queryMManufactureCheckAndNoProcedure.action")
    public PageVo<MManufacture> queryMManufactureCheckAndNoProcedure(@RequestBody Map<String,String> map){
        PageVo<MManufacture> mManufacturePageVo = mManufactureService.queryMManufactureCheckAndNoProcedure(map);
        return mManufacturePageVo;
    }
    @ResponseBody
    @PostMapping("/queryMDesignProcedureById")
    public MManufacture queryMDesignProcedureById(Integer mManufactureId){
        MManufacture mManufacture = mManufactureService.selectByPrimaryKey(mManufactureId);
        return mManufacture;
    }
    @ResponseBody
    @PostMapping("/queryMDesignProcedureById.action")
    public MManufacture queryMDesignProcedureByIdAction(Integer mManufactureId){
        MManufacture mManufacture = mManufactureService.selectByPrimaryKey(mManufactureId);
        return mManufacture;
    }
    @ResponseBody
    @PostMapping("/queryAllMManufacture.action")
    public  PageVo<MManufacture> queryAllMManufacture(@RequestBody Map<String,String> map){
        PageVo<MManufacture> pageVo = mManufactureService.queryAllMManufacture(map);
        return  pageVo;
    }
    @ResponseBody
    @PostMapping("/checkMManufacture.action")
    public int checkMManufacture(String mManufactureStr) throws IOException {
        MManufacture mManufacture = JSONObject.parseObject(mManufactureStr, MManufacture.class);
//        System.out.println(mManufacture);
        //未通过的派工单不可再编辑，但可以查询到，需要重新进行派工，重新设计后将产生新的派工单编号
        if(mManufacture.getCheckTag().equals("S001-2")){
            String applyIdGroup = mManufacture.getApplyIdGroup();
            String[] split = applyIdGroup.split("\\|");
//            System.out.println(Arrays.toString(split));
            for(int i=0;i<split.length;i++){
//                System.out.println(split[i]);
//                if(i%2==0){
                    MApply mApply = mApplyService.selectByPrimaryKey(Integer.valueOf(split[i]));
                    mApply.setManufactureTag("P001-0");
                    mApplyService.updateByPrimaryKeySelective(mApply);
//                }
            }

        //审核通过后要按工序生成相应的出库申请记录，出库详细理由数据格式为：“派工单号—工序名称”。
        }else if(mManufacture.getCheckTag().equals("S001-1")){
            DFile dFile = dFileService.selectByPID(mManufacture.getProductId());
//            System.out.println(dFile);
            //向出库表插数据
            SPay sPay = new  SPay();
            sPay.setReasonexact(mManufacture.getManufactureId()+"-"+mManufacture.getProductName());
            sPay.setAmountSum(mManufacture.getAmount());
            sPay.setRegister(mManufacture.getChecker());
            sPay.setRegisterTime(mManufacture.getRegisterTime());
            sPay.setCheckTag("S001-1");
                //商品总金额
            sPay.setCostPriceSum(Double.parseDouble(dFile.getLIST_PRICE()*mManufacture.getAmount()+""));
            sPay.setStoreTag("K002-0");
            sPay.setReason("R001-1");
            sPayService.insertSelective(sPay);
            //向出库明细表插数据
            List<MProcedureModule> mProcedureModules = mProcedureModuleService.queryMProcedureModuleByMManufactureId(mManufacture.getId());

            Integer amountSum=0;
            Double costPriceSum=0.0;
            for(int i=0;i<mProcedureModules.size();i++){
                MProcedureModule mProcedureModule = mProcedureModules.get(i);
                SPayDetails sPayDetails1 = sPayDetailsService.querySPayDetailsByParentIdByProductId1(sPay.getId(), mProcedureModule.getProductId());
//                System.out.println(sPayDetails1);
                if(sPayDetails1!=null){
//                    System.out.println(sPayDetails1);
                    sPayDetails1.setAmount(mProcedureModule.getAmount()+sPayDetails1.getAmount());
//                    System.out.println(sPayDetails1);
                    sPayDetailsService.updateByPrimaryKeySelective(sPayDetails1);
                }else{
                    SPayDetails sPayDetails = new SPayDetails();
                    sPayDetails.setParentId(sPay.getId());
                    sPayDetails.setProductId(mProcedureModule.getProductId());
                    sPayDetails.setProductName(mProcedureModule.getProductName());
                    sPayDetails.setAmount(mProcedureModule.getAmount());
                    sPayDetails.setCostPrice(mProcedureModule.getCostPrice());
                    sPayDetails.setSubtotal(mProcedureModule.getSubtotal());
                    sPayDetails.setPayTag("K002-1");
                    //暂时将mProcedureModuleId赋予spayDetails
                    sPayDetails.setProductDescribe(mProcedureModule.getId()+"");
                    sPayDetailsService.insertSelective(sPayDetails);
                }

                amountSum+=mProcedureModule.getAmount();
                costPriceSum+=mProcedureModule.getSubtotal();
            }
            sPay.setAmountSum(amountSum);
            sPay.setCostPriceSum(costPriceSum);
            sPayService.updateByPrimaryKeySelective(sPay);
        }
//        System.out.println(mManufacture);
        return mManufactureService.updateByPrimaryKeySelective(mManufacture);
    }
    @PostMapping("/queryMManufactureNoReCheck.action")
    public PageVo<MManufacture> queryMManufactureNoReCheck(@RequestBody Map<String,String> map){
        PageVo<MManufacture> pageVo = mManufactureService.queryMManufactureNoReCheck(map);
        return pageVo;
    }
    @PostMapping("/checkIfLastTransfer.action")
    public int checkIfLastTransfer(Integer mManufactureId, HttpSession session) throws IOException {
//        System.out.println(mManufactureId);
        MManufacture mManufacture = mManufactureService.selectByPrimaryKey(mManufactureId);
        mManufacture.setManufactureProcedureTag("S002-2");
        List<MProcedure> mProcedures = mProcedureService.queryMProcedureByPId(mManufactureId);
        Double realModuleCostPriceSum=0.0;
        Double realLabourCostPriceSum=0.0;
        for(int i=0;i<mProcedures.size();i++){
            MProcedure mProcedure = mProcedures.get(i);
            realModuleCostPriceSum+=mProcedure.getRealModuleSubtotal();
            realLabourCostPriceSum+=mProcedure.getRealSubtotal();
            if(i==mProcedures.size()-1){
                double realAmount = mProcedure.getRealAmount();
                int a=(int)realAmount;
                mManufacture.setTestedAmount(a);
            }
        }
        mManufacture.setRealModuleCostPriceSum(realModuleCostPriceSum);
        mManufacture.setRealLabourCostPriceSum(realLabourCostPriceSum);

        //如果是最后一个工序做完交接复核后，代表生产完毕，系统生成相应入库调度单
        SGather sGather = new SGather();
        //审核通过
        sGather.setCheckTag("S001-1");
        //库存标志：未审核
        sGather.setStoreTag("K002-0");
        sGather.setReason("R001-1");
        Serial serial = new Serial();
        serial.addUser("gatherId","402");
        String gatherId = serial.getNumber("gatherId", "402", "", "", "");
        sGather.setGatherId(gatherId);
        SysUsers user = (SysUsers) session.getAttribute("user");
        sGather.setStorer(user.getLoginId());
        sGather.setAmountSum(mManufacture.getTestedAmount());
        //入库的商品金额总计
        DFile dFile = dFileService.queryByProductId(mManufacture.getProductId());
        sGather.setCostPriceSum(dFile.getLIST_PRICE()*mManufacture.getTestedAmount());
        sGatherService.insertSelective(sGather);

        SGatherDetails sGatherDetails = new SGatherDetails();
        sGatherDetails.setParentId(sGather.getId());
        sGatherDetails.setProductId(dFile.getPRODUCT_ID());
        sGatherDetails.setProductName(dFile.getPRODUCT_NAME());
        sGatherDetails.setAmount(sGather.getAmountSum());
        sGatherDetails.setAmountUnit(dFile.getAMOUNT_UNIT());
        sGatherDetails.setCostPrice(Double.parseDouble(dFile.getLIST_PRICE()+""));
        sGatherDetails.setSubtotal(sGatherDetails.getCostPrice()*sGatherDetails.getAmount());
        sGatherDetails.setGatherTag("K002-1");
        sGatherDetailsService.insertSelective(sGatherDetails);

        return mManufactureService.updateByPrimaryKeySelective(mManufacture);

    }
    @PostMapping("/queryIfLastTransfer.action")
    public int queryIfLastTransfer(Integer mManufactureId){
        MManufacture mManufacture = mManufactureService.selectByPrimaryKey(mManufactureId);

        mManufacture.setManufactureProcedureTag("S002-2");

        return mManufactureService.updateByPrimaryKeySelective(mManufacture);

    }
    @PostMapping("/queryMManufacture.action")
    public PageVo<MManufacture> queryMManufacture(@RequestBody Map<String,String> map){
        PageVo<MManufacture> pageVo = mManufactureService.queryMManufacture(map);
        return pageVo;
    }
}
